﻿using UnityEngine;

public class Radar : MonoBehaviour
{
    //网格模型顶点数量
    private int VERTICES_COUNT;

    [Tooltip("边数为数组长度减1")]
    //顶点数组
    public Vector3[] vertices;
    //三角形数组
    int[] triangles;
    public float scale;
   

    MeshFilter meshFilter;
    Mesh mesh;

    float pi = 3.1415f;

    float sin72 = 0f;
    float cos72 = 0f;
    float sin54 = 0f;
    float cos54 = 0f;
    float sin36 = 0f;
    float cos36 = 0f;
    float sin18 = 0f;
    float cos18 = 0f;
    void Start()
    {
        sin72 = Mathf.Sin(GetRadians(72));
        cos72 = Mathf.Cos(GetRadians(72));
        sin54 = Mathf.Sin(GetRadians(54));
        cos54 = Mathf.Cos(GetRadians(54));
        sin36 = Mathf.Sin(GetRadians(36));
        cos36 = Mathf.Cos(GetRadians(36));
        sin18 = Mathf.Sin(GetRadians(18));
        cos18 = Mathf.Cos(GetRadians(18));

        CreateMesh();
        SetVertices();
    }

    void OnGUI()
    {
        if (meshFilter == null)
        {
            CreateMesh();
            SetVertices();
        }

        Apply();
        if (GUILayout.Button("Apply "))
        {
            Apply();
        }
    }

    void CreateMesh()
    {
        meshFilter = this.GetComponent<MeshFilter>();
        mesh = meshFilter.mesh;
    }

    float height = 50;
    void SetVertices()
    {
        //顶点
        vertices[0] = new Vector3(0, 0, 1);
        vertices[1] = new Vector3(0, height, 1);
        vertices[2] = new Vector3(-height * sin72, height * cos72, 1);
        vertices[3] = new Vector3(-height * cos54, -height * sin54, 1);
        vertices[4] = new Vector3(height * sin36, -height * cos36, 1);
        vertices[5] = new Vector3(height * cos18, height * sin18, 1);

        //三角形
        int triangles_count = vertices.Length - 1;
        triangles = new int[triangles_count * 3];

        triangles[0] = 0;
        triangles[1] = 1;
        triangles[2] = 2;

        triangles[3] = 0;
        triangles[4] = 2;
        triangles[5] = 3;

        triangles[6] = 0;
        triangles[7] = 3;
        triangles[8] = 4;

        triangles[9] = 0;
        triangles[10] = 4;
        triangles[11] = 5;

        triangles[12] = 0;
        triangles[13] = 5;
        triangles[14] = 1;
    }

    float GetRadians(float angle)
    {
        return pi / 180 * angle;
    }

    void Apply()
    {
        Vector3[] tmps = new Vector3[vertices.Length];
        for (int i = 0; i < vertices.Length; i++)
        {
            tmps[i] = vertices[i] * vertices[i].z * scale;
        }

        mesh.vertices = tmps;
        mesh.triangles = triangles;
    }
}
